package com.minsus.secretmailbox;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

public class C2DMReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(
				"com.google.android.c2dm.intent.REGISTRATION")) {
			handleRegistration(context, intent);
		} else if (intent.getAction().equals(
				"com.google.android.c2dm.intent.RECEIVE")) {
			handleMessage(context, intent);
		}
	}

	private void handleRegistration(Context context, Intent intent) {
		String registration = intent.getStringExtra("registration_id");
		SharedPreferences prefs = context.getSharedPreferences(
				context.getString(R.string.prefs_name), Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = prefs.edit();
		HttpClientPost httpClientPost = new HttpClientPost();

		if (intent.getStringExtra("error") != null) {
			Log.d("test", "test error=" + registration);
		} else if (intent.getStringExtra("unregistered") != null) {
			Log.d("test", "test unregistered id=" + registration);
			editor.remove(context.getString(R.string.prefs_registration_id));
		} else if (registration != null) {
			Log.d("test", "test registered id=" + registration);
			editor.putString(context.getString(R.string.prefs_registration_id),
					registration);
			String result = null;
			String resultMsg = null;
			try {
				result = httpClientPost.httpSetRegstrationId(context
						.getString(R.string.url_c2dm_register), Settings.Secure
						.getString(context.getContentResolver(),
								android.provider.Settings.Secure.ANDROID_ID),
						registration, android.os.Build.MODEL,
						android.os.Build.VERSION.RELEASE);

				if (result.endsWith("success")) {
					resultMsg = "푸시 기능 등록 완료!!";
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (resultMsg == null) {
				resultMsg = "푸시 기능 등록 실패~~";
			}

			Toast.makeText(context, resultMsg, Toast.LENGTH_SHORT).show();
		}
		editor.commit();
	}

	private void handleMessage(Context context, Intent intent) {
		Toast.makeText(context, "" + intent.getStringExtra("msg"),
				Toast.LENGTH_SHORT).show();
	}
} // end of class C2DMReceiver
